package com.aaa.ssm.controller;

import cn.hutool.core.io.FileUtil;
import com.aaa.ssm.util.ResultFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.util.IdUtil;

import java.io.File;
import java.io.IOException;

/**
 * @ fileName:FileController
 * @ description:
 * @ author:张圣福
 * @ createTime:2023/10/18 11:13
 * @ version:1.0.0
 */
@RestController
@RequestMapping("/files")
public class FileController {
    /**
     * 上传接口
     *
     * @param file
     * @return
     * @throws
     */
    /**
     * 上传接口
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultFile<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        //String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        // 定义文件的唯一标识（前缀）
        File file1 = new File("webapp/files");
        String path = file1.getPath();
        System.out.println(path+"====================11111======================");

        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/"
                + flag + "_" + originalFilename;  // 获取上传的路径
        System.out.println(rootFilePath+".................");
        File rootFile = new File(path);
        if (!rootFile.getParentFile().exists()) {
            rootFile.getParentFile().mkdirs();
        }
        FileUtil.writeBytes(file.getBytes(), rootFilePath);  // 把文件写入到上传的路径
        return ResultFile.success("http://" + "localhost" + ":" + 9090 + "/webapp/files/" + flag + "_" + originalFilename);  // 返回结果 url
    }
}